package com.example.first;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class MyTask implements Runnable{
    private final String TAG="mytask";
    private Handler handler;
    private String logDate="";
    public Handler getHandler() {
        return handler;
    }
    public void setHandler(Handler handler) {
        this.handler = handler;
    }
    @Override
    public void run() {
        Log.i(TAG, "run:run()....");
        List<HashMap<String,String>> relist=new ArrayList<HashMap<String,String>>();
        String curDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
        Log.i(TAG, "run: curDatestr"+curDateStr+"logDate"+logDate);
        if(curDateStr.equals(logDate)){
            Log.i(TAG, "run: 日期相等，从数据库中获取数据");
        }
        try {
            Document doc = Jsoup.connect("https://www.boc.cn/sourcedb/whpj/").get();
            Elements tables = doc.getElementsByTag("table");
            Elements trs = tables.get(1).getElementsByTag("tr");
            trs.remove(0);
            for (Element tr : trs) {
                Elements tds = tr.getElementsByTag("td");
                if (tds.size() > 0) {
                    Element td1 = tds.first();
                    Element td2 = tds.get(5);
                    String str1 = td1.text();
                    String str2 = td2.text();
                    Log.i(TAG, "run:" + str1 + "==>" + str2);
                    HashMap<String,String> map = new HashMap<String,String>();
                    map.put("cname",str1);
                    map.put("cval",str2);
                    relist.add(map);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Message msg = handler.obtainMessage(5); //发送消息
        msg.obj = relist;
        handler.sendMessage(msg);
        Log.i(TAG, "run:sendMessage");
    }
}
